#include "Cserver.h"
const char* pHtml = R"(
<form id="formElem">
 <input type="text" name="id" id="txt1" placeholder"input id">
 <input type="text" name="name" id="txt2" placeholder"input name">
 <input type="submit">
</form>
<script>
 formElem.onsubmit=async (e) =>{
   e.preventDefault();
   var c_id=document.getElementById("txt1").value;
   var c_name=document.getElementById("txt1").value;
   const user={id:c_id,name:c_name};
   let response=awit fetch('/post',{
     methos: 'POST',
     body: JSON.stringify(user)
   });
   let result=await response.json();
   alert(result.message);
   };
</script>
)";//网页客户端html界面

CServer::CServer()
{
	mysql_init(&m_serverMysql);		//初始化数据库
	mysql_options(&m_serverMysql,MYSQL_SET_CHARSET_NAME,"gbk");
	m_serverHeader = {
		{"content-type","application/json"}
	};
}

CServer::~CServer()
{
	m_serverManager.stop();			//关闭服务端
}

void CServer::DoServer()
{
	/*连接数据库，接收客户端发送来的信息，开启服务端监听，关闭数据库*/
	LinkToDatabase();
	ReceFromClient();
        StartUpListen();
	mysql_close(&m_serverMysql);
}

void CServer::LinkToDatabase()
{
	/*连接数据库*/
	if (mysql_real_connect(&m_serverMysql,"127.0.0.1","root","193193","httpbase",3306,NULL,0)==NULL)
	{
		std::cout<<"数据库连接失败"<<mysql_error(&m_serverMysql)<<std::endl;
		exit(-1);
	}
	std::cout<<"数据库连接成功"<<std::endl;
}

void CServer::ReceFromClient()
{
	/*接收客户端请求*/
   ReceGet();

   RecePut();
   
   RecePost();
   
   ReceDelete();
}

void CServer::ReceDelete()
{
  m_serverManager.Delete("/delete",[this](const httplib::Request& req,httplib::Response& res)
		  {
		    auto strType = req.method;				  //输出客户端发送请求类型
		    std::cout<<"type:"<<strType<<std::endl;
		    auto strBody = req.body;				  //输出客户端请求的正文
		    std::cout<<strBody<<std::endl;
		    nlohmann::json jsonStr = nlohmann::json::parse(strBody);//将字符串转化为json格式
		    std::string strDeleteId = jsonStr["id"];		  //获取json中id的字段
		    std::string strDeleteName = jsonStr["name"];
		    std::string strDeleteSql = "delete from httptable where ";//拼接mysql语句
		    if (strDeleteId != "NULL")				   
		    {
		       if (strDeleteName == "NULL")
		       {
		         strDeleteSql += "h_id=" + strDeleteId;
		       }
		       else
		       {
		         strDeleteSql += "h_id=" + strDeleteId + " and h_name=\"=" + strDeleteName+"\"";
		       }
		    }
		    else
		    {
			    strDeleteSql += "h_name=\"= "+ strDeleteName + "\"";
		    }
		    const char* pSql = strDeleteSql.c_str();		//将string类型转换为const char*
		    std::cout<<strDeleteSql<<std::endl;
		    int iResult = mysql_query(&m_serverMysql,pSql);	//执行拼接的mysql语句
		    if (iResult)					//返回提示给客户端
		    {
			    res.body = "删除数据失败";
			    std::cout<<"删除数据失败"<<std::endl;
		    }
		    else
		    {
			    res.body="成功删除数据";
			    std::cout<<"成功删除数据"<<std::endl;
		    }

		  });
}

void CServer::RecePost()
{
	/*当接收到客户端发送增加数据的请求*/
   m_serverManager.Post("/post",[this](const httplib::Request& req,httplib::Response& res)
   {
		   std::cout<<"客户端发送post插入请求"<<std::endl;
		   std::cout<<"type:"<<req.method<<std::endl;
		   auto strBody = req.body;
		   std::cout<<strBody<<std::endl;
		   nlohmann::json JsonStr = nlohmann::json::parse(strBody);//将字符串转化为json个格式
		   std::string strPostId = JsonStr["id"];		//获取json中id的字段
		   std::string strPostName = JsonStr["name"];
		   std::string strPostSql = "insert into httptable value(";//拼接mysql语句
		   strPostSql += strPostId + ",\"" + strPostName + "\")";
		   const char* pSql = strPostSql.c_str();			//将string类型转换为const char*类型
		   std::cout<<pSql<<std::endl;
		   int iResult = mysql_query(&m_serverMysql,pSql);
		   if (iResult)
		   {
		   res.body = "插入数据失败，id重";
		   std::cout<<"插入数据失败"<<std::endl;
		   }
		   else
		   {
			   res.body = "成功插入数据";
			   std::cout<<"成功插入数据"<<std::endl;
		   }
		   });
}
void CServer::RecePut()
{
	/*当接收到客户大un发送的更新数据请求的时候*/
	m_serverManager.Put("/update",[this](const httplib::Request& req,httplib::Response& res)
			{
			   std::cout<<"客户端发来update更新数据请求"<<std::endl;
			   auto strType = req.method;
			   std::cout<<"type:"<<strType<<std::endl;
			   auto strBody = req.body;
			   std::cout<<strBody<<std::endl;
			   nlohmann::json jsonStr=nlohmann::json::parse(strBody);//将字符串转化为json格式
			   std::string strUpId = jsonStr["id"];			//获取json串中id的字段
			   std::string strUpName = jsonStr["name"];
			   std::string strUpSql = "update httptable set h_name=\""; //拼接mysql语句
			   strUpSql+=strUpName+"\" where h_id=" + strUpId;
			   const char* pSql = strUpSql.c_str();			//将string类型转换为const char*类型
			   std::cout<<strUpSql<<std::endl;
			   int result = mysql_query(&m_serverMysql,pSql);	//执行mysql语句
			   if (result)		 	//返回执行结果到客户端
			   {
			   res.body = "更新数据失败";
			   std::cout<<"更新数据失败"<<std::endl;
			   }
			   else
			   {
				   res.body = "成功更新数据";
				   std::cout<<"成功更新数据"<<std::endl;
			   }
			});
}

void CServer::ReceGet()
{
	
	/*当接收到网页客户端发送的查询数据库的请求*/
  m_serverManager.Get("/submit",[](const httplib::Request& req,httplib::Response& res)
	{
	 res.set_content(pHtml,"text/html");		//设置接收的内容为html
	 });
	m_serverManager.Get("/mysql",[this](const httplib::Request& req,httplib::Response& res)
		{
		 std::cout<<"客户端发送get查询数据库请求-HTML"<<std::endl;
		 std::cout<<"type:"<<req.method<<std::endl;
		 const char* pSql = "select * from httptable";
		 std::string strHtml=R"(<form if="formElem1">)";//拼接html
		 mysql_query(&m_serverMysql,pSql);		//执行mysql语句
		 m_pServerRes = mysql_store_result(&m_serverMysql);	//接收结果集
		 int iCount = 0;	//结果的行数
		 while (m_serverSqlRow = mysql_fetch_row(m_pServerRes))
		 {
		     int iNum = mysql_num_fields(m_pServerRes);		//一行有几列
		     std::string str1;
		     std::string str2;
		     nlohmann::json jSql;	//拼接html语句
		     for (int j = 0;j < iNum;++j)
		     {
		      if (j == 0)
		      {
		        str1 = m_serverSqlRow[j];
			jSql["id"] = str1;
		      }
		      else
		      {
			      str2 = m_serverSqlRow[j];
			      jSql["name"] = str2;
		      }
		     }
		     std::cout<<"jSql:"<<jSql<<std::endl;
		     strHtml += R"(<p><input type="text" name="id" value=)";
		     strHtml += jSql["id"];
		     strHtml += R"(>
                     <input type="text" name="name" value=)";
		     strHtml += jSql["name"];
		     strHtml += R"(></p>)";
		     iCount++;
		 }
		 strHtml += R"(</form>)"; 	//html语句拼接完成
		 mysql_free_result(m_pServerRes);	//释放结果集
		 res.set_content(strHtml,"text/html");
		});
	/*pc客户端发送查询请求的时候*/
   m_serverManager.Get("/mysqlclient",[this](const httplib::Request& req,httplib::Response& res)
		{
		 std::cout<<"客户端发送get查询数据库请求-client"<<std::endl;
                 std::string strResult;
		 std::cout<<"type:"<<req.method<<std::endl;
		 const char* pSql = "select * from httptable";		//执行mysql语句
		 mysql_query(&m_serverMysql,pSql);
		 m_pServerRes = mysql_store_result(&m_serverMysql);	//接收结果集
		 int iCount = 0; 		//结果有几行
		 while (m_serverSqlRow = mysql_fetch_row(m_pServerRes)) //拼接返回到客户端的文本
		 {
		     int iNum = mysql_num_fields(m_pServerRes);		//一行有几列
		     std::string str1;
		     std::string str2;
		     nlohmann::json jSql;
		     for (int j = 0;j < iNum;++j)
		     {
		      if (j == 0)
		      {
		        str1 = m_serverSqlRow[j];
			jSql["id"] = str1;
                        strResult += "id:";
                        strResult += str1;
		      }
		      else
		      {
			      str2 = m_serverSqlRow[j];
			      jSql["name"] = str2;
			      strResult += '\t';
                              strResult += "name:";
			      strResult += str2;
			      strResult += '\n';
		      }
		     }
		     
		     iCount++;
		 }
                 std::cout<<"result:"<<strResult<<std::endl;
		 mysql_free_result(m_pServerRes);
		 res.set_content(strResult,"text/plain");	//设置返回结果为文本格式
		});
}

void CServer::StartUpListen()
{
	/*服务端开启监听*/
	m_serverManager.listen("localhost",1234);
}

